package controller

import (
	"ginblog/enum"
	"ginblog/middleware"
	"ginblog/model"
	"ginblog/resp"
	"ginblog/service"
	"github.com/gin-gonic/gin"
	"net/http"
)

type LoginController struct {
	login service.UserService
	r     resp.Resp
	jwt   middleware.JWT
}

type LoginConInterface interface {
	Login(c *gin.Context)
}

// Login 用户登录
func (l LoginController) Login(c *gin.Context) {
	// 获取用户传递得到数据
	user := model.User{}
	err := c.ShouldBind(&user)
	if user.Username == "" && user.Password == "" {
		l.r.RespData(enum.ERROR, enum.ERROR.String(), "数据格式有误！", c)
		return
	}

	if err != nil {
		l.r.RespData(enum.ERROR, enum.ERROR.String(), "数据格式有误！", c)
		return
	}

	username, code := l.login.CheckLogin(user.Username, user.Password)

	if code != enum.SUCCESS {
		l.r.RespData(code, code.String(), "", c)
		return
	}
	// 生成token
	token, code1 := l.jwt.SetToken(user.Username)
	if code1 != enum.SUCCESS {
		l.r.RespData(code1, code1.String(), "", c)
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"status":   code1,
		"message":  code1.String(),
		"username": username,
		"token":    token,
	})
}
